package me.xiaoyan.android.net;

import java.util.ArrayList;

import android.text.TextUtils;

/**
 * 获取网络数据 传递的参数类
 * @author xiaoyan
 *
 */
public class WebParameters {
	private ArrayList<String> wpKeys = new ArrayList<String>();
	private ArrayList<String> wpValues = new ArrayList<String>();

	public WebParameters() {

	}

	public WebParameters(String key, String value) {
		this.add(key, value);
	}

	public WebParameters add(String key, String value) {
		if (!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value)) {
			this.wpKeys.add(key);
			wpValues.add(value);
		}
		return this;
	}

	public WebParameters add(String key, int value) {
		this.wpKeys.add(key);
		this.wpValues.add(String.valueOf(value));
		return this;
	}

	public WebParameters add(String key, long value) {
		this.wpKeys.add(key);
		this.wpValues.add(String.valueOf(value));
		return this;
	}

	public void remove(String key) {
		int firstIndex = wpKeys.indexOf(key);
		if (firstIndex >= 0) {
			this.wpKeys.remove(firstIndex);
			this.wpValues.remove(firstIndex);
		}

	}

	public void remove(int i) {
		if (i < wpKeys.size()) {
			wpKeys.remove(i);
			this.wpValues.remove(i);
		}

	}

	private int getLocation(String key) {
		if (this.wpKeys.contains(key)) {
			return this.wpKeys.indexOf(key);
		}
		return -1;
	}

	public String getKey(int location) {
		if (location >= 0 && location < this.wpKeys.size()) {
			return this.wpKeys.get(location);
		}
		return "";
	}

	public String getValue(String key) {
		int index = getLocation(key);
		if (index >= 0 && index < this.wpKeys.size()) {
			return this.wpValues.get(index);
		} else {
			return null;
		}
	}

	public String getValue(int location) {
		if (location >= 0 && location < this.wpKeys.size()) {
			String rlt = this.wpValues.get(location);
			return rlt;
		} else {
			return null;
		}

	}

	public int size() {
		return wpKeys.size();
	}

	public void addAll(WebParameters parameters) {
		for (int i = 0; i < parameters.size(); i++) {
			this.add(parameters.getKey(i), parameters.getValue(i));
		}

	}

	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < this.wpKeys.size(); i++) {
			sb.append("&" + wpKeys.get(i) + "=" + wpValues.get(i));
		}
		String str = sb.toString();
		return str.length() > 0 ? str.substring(1) : "";
	}

	public void clear() {
		this.wpKeys.clear();
		this.wpValues.clear();
	}
}
